package jdbc;

import lombok.SneakyThrows;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Objects;

/**
 * @classname:DBHelper
 * @description:
 * @author: Mr.Z
 * @date: 2020/12/28 9:16
 * @version: 0.1
 * @since:1.8
 */
public class DBHelper {
    private DBHelper(){}


    private static final ThreadLocal<Connection> THREAD_LOCAL = new ThreadLocal(){
        @Override
        @SneakyThrows
        protected Object initialValue() {
            return DriverManager.getConnection(PropUtil.getValue("url"),PropUtil.getValue("username"),PropUtil.getValue("password"));
        }
    };

    public static Connection getCon(){
        return THREAD_LOCAL.get();
    }

    public static void closeResources(Connection connection){
        Objects.requireNonNull(connection);
        THREAD_LOCAL.remove();
        try {
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }



}
